﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace NMigrate
{
	public class FileName
	{
		public static FileName Parse(FileInfo file, bool numberOptional = false)
		{
			var components = file.Name.Split('.');
			int version = -1;
			if(int.TryParse(components[0], out  version))
			{
				if(components.Length < 3)
					throw new InvalidOperationException("File name with version number should have at least 3 components (like 1.hello.txt)");
				return new FileName(version, GetMiddle(1, components), components[components.Length - 1], file);
			}
			if(!numberOptional)
				return null;

			if(components.Length < 2)
				throw new InvalidOperationException("File name without version number should have at least 2 component (like hello.txt)");
			return new FileName(-1, GetMiddle(0, components), components[components.Length - 1], file);
		}

		private static string GetMiddle(int startIndex, string[] components)
		{
			return String.Join(".", components.Where((c, i) => i >= startIndex && i != components.Length - 1));
		}

		public FileName(int number, string name, string extension, FileInfo file)
		{
			_Number = number;
			_Name = name;
			_Extension = extension;
			_File = file;
		}

		private readonly int _Number;
		public int Number
		{
			get
			{
				return _Number;
			}
		}
		private readonly string _Name;
		public string Name
		{
			get
			{
				return _Name;
			}
		}
		private readonly string _Extension;
		public string Extension
		{
			get
			{
				return _Extension;
			}
		}
		private readonly FileInfo _File;
		public FileInfo File
		{
			get
			{
				return _File;
			}
		}
	}
}
